package master_worker;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by brossd ong on 2018/1/20.
 */
public class Master {

    //1 使用ConcurrentLinkedQueue承载所有任务
    private ConcurrentLinkedQueue<Task> workQueue = new ConcurrentLinkedQueue<Task>();
    //2 使用HashMap<String,Thread>承载所有worker对象
    private HashMap<String,Thread> workers = new HashMap<String, Thread>();
    //3 使用ConcurrentHashMap<String,Object>承载每一个任务的结果集
    private ConcurrentHashMap<String,Object> resultMap = new ConcurrentHashMap<String, Object>();

    //构造方法
    public Master(Worker worker,int workerCount) {
        //每一个worker对象都需要Master对象的引用
        //workerQueue用于任务领取
        //resultMap用于任务提交
        worker.setWorkerQueue(this.workQueue);
        worker.setResultMap(this.resultMap);

        for (int i = 0;i < workerCount;i++) {
            //key表示每一个worker的名字,value表示线程执行的对象
            workers.put("子节点" + Integer.toString(i),new Thread(worker));
        }
    }

    //提交方法
    public void submit(Task task) {
        this.workQueue.add(task);
    }

    //需要一个执行方法,(启动程序,让所有worker工作)
    public void execute() {
        for (Map.Entry<String,Thread> me : workers.entrySet()) {
            me.getValue().start();
        }
    }

    //判断线程是否执行完毕
    public boolean isComplete() {
        for (Map.Entry<String,Thread> me : workers.entrySet()) {
            if (me.getValue().getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

    //返回结果集数据
    public int getResult() {
        int ret = 0;
        for (Map.Entry<String,Object> me : resultMap.entrySet()) {
            //汇总逻辑
            ret += (Integer) me.getValue();
        }
        return ret;
    }
}
